1666J - Job Lookup - CodeForces Solution


constructive algorithms dp shortest paths trees *2100

Please click on ads to support us..

C++ Code:

#include <algorithm>
#include <iostream>

using namespace std;
using LL = long long;
using PII = pair<int, int>;

const int MAXN = 200 + 3;
const LL Inf = 2e17;

struct DP{
  LL w;
  int root;
}dp[MAXN][MAXN];

int n, ans[MAXN];
LL a[MAXN][MAXN], sum[MAXN][MAXN];
LL ssum[MAXN][MAXN];

void dfs(int l, int r, int dad){
  if(l > r) return;
  ans[dp[l][r].root] = dad;
  dfs(l, dp[l][r].root - 1, dp[l][r].root);
  dfs(dp[l][r].root + 1, r, dp[l][r].root);
}

int main(){
  cin >> n;
  for(int i = 1; i <= n; i++){
    for(int j = 1; j <= n; j++){
      cin >> a[i][j];
      sum[i][j] = sum[i][j - 1] + a[i][j];
      ssum[i][j] = ssum[i - 1][j] + sum[i][j];
      dp[i][j].w = Inf, dp[i][j].root = -1;
    }
  }
  for(int i = 1; i <= n; i++) dp[i][i].w = 0, dp[i][i].root = i;
  for(int l = 2; l <= n; l++){
    for(int i = 1; i <= n - l + 1; i++){
      int j = i + l - 1;
      for(int m = i; m <= j; m++){
        LL _w = (i < m ? dp[i][m - 1].w : 0) + (m < j ? dp[m + 1][j].w : 0);
        _w += (ssum[m-1][n] - ssum[i-1][n]) + (ssum[m-1][i-1] - ssum[i-1][i-1]) - (ssum[m-1][m-1] - ssum[i-1][m-1]);
        _w += (ssum[j][n] - ssum[m][n]) + (ssum[j][m] - ssum[m][m]) - (ssum[j][j] - ssum[m][j]);
        if(_w < dp[i][j].w) dp[i][j].w = _w, dp[i][j].root = m;
      }
    }
  }
  dfs(1, n, 0);
  for(int i = 1; i <= n; i++){
    cout << ans[i] << " ";
  }
  return 0;
}
/*
5
4 1 5 3 4


*/

	 	 		 	 	 	  	    	 				 		


Comments

Submit
0 Comments
More Questions

1717B - Madoka and Underground Competitions
61B - Hard Work
959B - Mahmoud and Ehab and the message
802G - Fake News (easy)
1717C - Madoka and Formal Statement
420A - Start Up
1031A - Golden Plate
1559C - Mocha and Hiking
427B - Prison Transfer
330A - Cakeminator
426A - Sereja and Mugs
363A - Soroban
1585C - Minimize Distance
1506E - Restoring the Permutation
1539A - Contest Start
363D - Renting Bikes
1198D - Rectangle Painting 1
1023B - Pair of Toys
1725A - Accumulation of Dominoes
1675E - Replace With the Previous Minimize
839A - Arya and Bran
16B - Burglar and Matches
1625B - Elementary Particles
1725G - Garage
1725B - Basketball Together
735A - Ostap and Grasshopper
1183B - Equalize Prices
1481A - Space Navigation
1437B - Reverse Binary Strings
1362B - Johnny and His Hobbies